package com.caiwangdai.app.origin

import android.app.Activity
import android.content.*
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.ViewGroup
import com.caiwangdai.app.Const
import com.caiwangdai.app.R
import com.caiwangdai.app.extension.isUserLogined
import com.caiwangdai.app.extension.launchLoginPage
import com.caiwangdai.app.origin.back.BackHandlerHelper
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

/**
 * @author 艹羊
 * @project KotLinProject
 * @date 2017/6/5 下午6:06
 * @description
 */


abstract class BaseActivity : AppCompatActivity() {
    lateinit var WMContent: ViewGroup
    lateinit var mContext: Context


    var disposableList: CompositeDisposable = CompositeDisposable()

    protected abstract fun getLayoutResID(): Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutResID())
        initBase()
        initConfig()
        initData()
        initView()
    }


    private fun initBase() {
        mContext = this
        WMContent = window.decorView.findViewById(android.R.id.content)
    }

    open fun initConfig() {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT//请求为竖直屏幕
    }

    //初始化数据
    open fun initData() {}

    //初始化视图
    open fun initView() {}


    override fun startActivityForResult(intent: Intent?, requestCode: Int) {
        super.startActivityForResult(intent, requestCode)
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out)
    }

    //需要登录
    fun isNeedLogin(): Boolean {
        if (!isUserLogined()) {
            launchLoginPage()
            return true
        }
        return false
    }

    override fun onBackPressed() {
        if (!BackHandlerHelper.handleBackPress(this)) {
            finish()
        }
    }


    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out)
    }


    override fun onDestroy() {
        super.onDestroy()
        disposableList.clear()
    }


    fun addDisposable(d: Disposable) {
        disposableList.add(d)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == Const.INTENT_REQUEST_LOGIN) {
            if (resultCode == Activity.RESULT_OK) onLoginSuccess() else onLoginCancel()
            return
        }
        super.onActivityResult(requestCode, resultCode, data)

    }

    //身份过期后的操作
    open fun onLoginSuccess() {}

    open fun onLoginCancel() {}

}
